package com.zzyl.intercept;

import cn.hutool.core.util.StrUtil;
import com.zzyl.config.JwtTokenManagerProperties;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 多租户放到SubjectContent上下文中
 */
@Component
public class AdminIntercept implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否是HandlerMethod，不是放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //2.获取请求头的token
        String token = request.getHeader(Constants.USER_TOKEN);
        //3.判断token是否为null，为null抛出异常
        if (StrUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //4.解析token，得到载荷
        Claims claims = JwtUtil.parseJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                token
        );
        //5.获取用户数据，写入线程
        String json = claims.get("currentUser").toString();
        UserThreadLocal.setSubject(json);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除当前线程中的参数
        UserThreadLocal.removeSubject();
    }
}